<template>
  <el-dialog :title="dialogTitle" :visible="isVisible" width="30%" @close="handleClose">
    <!-- 表单内容 -->
    <el-form ref="form" :model="formData" :rules="rules">
      <el-form-item label="商户名称" prop="businessesName">
        <el-input v-model="formData.businessesName"></el-input>
      </el-form-item>
      <el-form-item label="商户编码" prop="businessesCode">
        <el-input v-model="formData.businessesCode"></el-input>
      </el-form-item>
      <el-form-item label="所在城市" prop="cityCode">
        <el-cascader
          style="width: 100%"
          clearable
          filterable
          v-model="formData.cityCode"
          :options="options"
          @change="handleChange"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="负责人姓名" prop="leader">
        <el-input v-model="formData.leader"></el-input>
      </el-form-item>
      <el-form-item label="负责人联系方式" prop="leaderPhone">
        <el-input v-model="formData.leaderPhone"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" :rows="5" v-model="formData.remark"></el-input>
      </el-form-item>

      <!-- 操作按钮区域 -->
      <div class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script>
import { getRegionTree } from '@/api/common';
import { addBusinesses, updateBusinesses } from '@/api/businesses';

export default {
  props: {
    // 接收来自父组件（/businesses/index.vue）的数据
    initialData: {
      type: Object,
      default: () => ({}),
    },
    dialogTitle: {
      type: String,
      default: '新增商户',
    },
    isEditing: {
      type: Boolean,
      default: false,
    },
    isVisible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      formData: {
        id: null, // 商户id
        businessesName: '', // 商户名称
        businessesCode: '', // 商户编码
        leader: '', // 负责人姓名
        leaderPhone: '', // 负责人联系方式
        remark: '', // 备注
      },
      rules: {
        businessesName: [{ required: true, message: '商户名称不能为空', trigger: 'blur' }],
        businessesCode: [{ required: true, message: '商户编码不能为空', trigger: 'blur' }],
        leader: [{ required: true, message: '负责人姓名不能为空', trigger: 'blur' }],
        leaderPhone: [{ required: true, message: '负责人联系方式不能为空', trigger: 'blur' }],
        cityCode: [{ required: true, message: '请选择所在城市', trigger: 'change' }],
      },
      options: [], // 省市区数据
    };
  },
  created() {
    this.getRegionTree();
  },
  watch: {
    isVisible(newVal) {
      if (newVal) {
        // 如果是新增，清空表单数据
        if (!this.isEditing) {
          this.formData = {};
        } else if (this.isEditing) {
          this.formData = { ...this.initialData };
        }
      }
    },
  },
  methods: {
    handleClose() {
      this.$emit('update:isVisible', false);
      this.$emit('close');
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 提交数据到后端接口，根据isEditing决定是新增还是更新商户
          const method = this.isEditing ? 'editBusinesses' : 'addBusinesses';
          this[method](this.formData);
        } else {
          this.$message.error('请填写完整信息');
        }
      });
    },
    async getRegionTree() {
      const res = await getRegionTree(2);
      // 将原始数据转换为 el-cascader 需要的格式
      this.options = this.formatOptions(res.data);
    },
    formatOptions(data) {
      // 将原始数据转化为 el-cascader 组件所需的嵌套结构
      return data.map((item) => ({
        value: item.code, // 或者根据实际情况可能是 item.id
        label: item.name,
        ...(item.child && { children: this.formatOptions(item.child) }), // 使用展开运算符(...)仅在item.child存在时添加children属性
      }));
    },
    handleChange(value) {
      const selectedLabels = value.map((item) => this.getLabelByValue(item, this.options));
      this.formData.province = selectedLabels[0];
      this.formData.city = selectedLabels[1];
    },
    getLabelByValue(value, options) {
      for (const option of options) {
        if (option.value === value) {
          return option.label;
        }
        if (option.children) {
          const childLabel = this.getLabelByValue(value, option.children);
          if (childLabel) {
            return childLabel;
          }
        }
      }
      return '';
    },
    async addBusinesses(data) {
      await addBusinesses(data).then(() => {
        this.$message.success('新增成功');
        // 关闭窗口刷新页面
        this.$emit('dialogCallBack');
      });
    },
    async editBusinesses(data) {
      await updateBusinesses(data).then(() => {
        this.$message.success('更新成功');
        this.$emit('dialogCallBack');
      });
    },
  },
};
</script>
